<template>
  <div class="simulationMain">
    <div class="questionWrap"
         v-if="questionList.length"
         :class='{"hide":lastQuestion||showQuestion}'>
      <div class="question">
        <div class="questionNum">
          <p class="p1"
             :data-id=questionList.length&&questionList[index].id>第{{index+1}}题</p>
        </div>
        <div class="questionContent">
          <div class="questionTitle">
            {{questionList.length&&questionList[index].question}}
          </div>
          <div class="questionAnswer"
               :data-answer=questionList.length&&questionList[index].answer>
            <!-- <div v-for="(value,key) in questionList.length&&questionList[index].answer_list" :key=key   > -->
            <div v-for="(value,key) in questionList.length&&answer_list"
                 :key=key>
              <p @click.stop="choise(index,key,questionList[index].id)"
                 :class='{"right":questionList[index].res ==key}'>
                <span>{{options[key]}}</span>
                {{value}}
              </p>
            </div>
          </div>
        </div>
      </div>
      <div class="questionBtn">
        <span class="prev"
              @click.stop="prevQuestion"
              :class='{"disabled": index==0}'
              :disabled='index==0'>上一题</span>

        <span class="next"
              @click.stop="nextQuestion">下一题</span>
      </div>
    </div>
    <div v-if="noData"
         class="noData">
      <img :src=noDataPng>
    </div>
    <div class="examOver"
         :class="showExamOver">
      <img :src=examBg
           alt=""
           class="examBg">
      <p class="tips">一共{{questionList.length}}道题，
        <span v-if='count ==questionList.length'>已全部作答</span>
        <span v-else>还有{{questionList.length-count }}道题未作答</span>
      </p>
      <div class="questionBtn">
        <span @click.stop="navToMenu(true)">查看答题卡</span>
        <span class="next"
              @click.stop="navToScore">提交试卷</span>
      </div>
    </div>
    <div class="markBottom"
         :class='{"hide": lastQuestion}'>
      <p class="iconfont icon-love"
         @click.stop="addToCollect(index,questionList[index].id)"
         :data-col='questionList.length&&questionList[index].collection'
         :class='{"collectActive":questionList.length && questionList[index].collection*1 ===1}'></p>
      <p class="iconfont icon-tubiaozhizuomoban"
         @click.stop="navToMenu(false)"></p>
      <p class="iconfont icon-timer">
        <span>{{startHour}}:{{startMin}}:{{startSecond}}</span>
      </p>
      <p>
        <button class="iconfont  icon-share2"
                :data-id=testpaperId
                open-type="share"></button>
      </p>
    </div>
    <!-- 答题部分 -->
    <div class="menuMain "
         :class='{"showmenuMain":showmenuMain}'>
      <div class="topicSelect">
        <div class="singleSelection">
          <p class="title">1.单选题</p>
          <div class="singleList">
            <span v-for="(el,i) in MultiSelection"
                  :key=i
                  @click.stop="addActive(i)"
                  :class="el.active ?'active':''">{{i+1}}</span>
          </div>
        </div>

      </div>
      <div class="fixedBtn">
        <span @click.stop=naviBack>继续练习</span>
        <span @click.stop="navToScore">提交试卷</span>
      </div>
    </div>
  </div>
</template>
  <script>
import { mapState, mapMutations } from 'vuex'
import { formatTime } from '@/utils'
export default {
  data () {
    return {
      index: 0,
      lastQuestion: false,
      showQuestion: false,
      startTimeStamp: 0,
      startSecond: 0,
      startMin: 0,
      startHour: 0,
      timer: null,
      commitAnswer: [],
      examRecord: [],
      commitItem: -1, // 试卷的某一道题
      examPaperId: -1, // 选择考卷的id
      showBottom: false, // 最后一页 隐藏底部工具
      clickAnswer: '',
      showmenuMain: false, // 展示菜单页面
      MultiSelection: [], // 答题选项
      currentIndex: -1,
      commitKey: '',
      count: 0,
      rightTotal: 0,
      totalTime: '',
      rightAnswerArray: [],
      questionList: [],
      options: ['A', 'B', 'C', 'D'],
      user_answer_list: [],
      error_list: [],
      noDataPng: './../../static/images/noData.png',
      examBg: './../../static/images/examBg.png',
      testpaperId: -1,
      noData: false
    }
  },
  onShareAppMessage (options) {
    console.log(options)
    this.shareId = options.target.dataset.id
    if (options.target.dataset.id) {
      return {
        title: '答题',
        path: '/pages/sharePage/main?shareId=' + options.target.dataset.id
      }
    }
  },
  computed: {
    ...mapState({
      device: state => state.device,
      randomRecord: state => state.randomRecord,
      formalRecord: state => state.formalRecord,
      userInfo: state => state.userInfo
    }),
    height () {
      return this.device.height
    },
    showExamOver () {
      if (this.showmenuMain || this.showQuestion) {
        return 'hide'
      } else if (this.lastQuestion) {
        return 'show'
      } else {
        return ''
      }
    },
    answer_list () {
      let that = this
      return that.questionList.length && Object.keys(that.questionList[that.index].answer_list).map(key => that.questionList[that.index].answer_list[key]).sort((a, b) => {
        return a.localeCompare(b)
      })
    }
  },
  methods: {
    ...mapMutations(['setExamPaper', 'setrandomRecord', 'setformalRecord', 'setExamResult']),
    choise (index, key, id) {
      // console.log(index, key, id)  // 0 D 3
      // console.log(this.options.indexOf(this.questionList[index].answer))
      if (key === this.options.indexOf(this.questionList[index].answer)) {
        this.user_answer_list.push({
          id: id,
          res: this.options.indexOf(this.questionList[index].answer)
        })
        this.user_answer_list = this.arrayUnique2(this.user_answer_list, 'id')
      } else {
        this.error_list.push({
          id: id,
          res: key,
          index: index

        })
        this.error_list = this.arrayUnique2(this.error_list, 'id')
      }
      this.questionList[index].hide = false
      this.clickAnswer = this.options[key]
      // 当前答的是哪一道题
      this.commitAnswer.push({
        index: index,
        id: this.questionList[index].id,
        res: key,
        right: this.commitKey === this.options.indexOf(this.questionList[this.index].answer) ? 1 : 0

      })
      this.commitAnswer = this.arrayUnique2(this.commitAnswer, 'id')
      // this.commitAnswer[index] = key
      this.questionList[index].res = key
      this.questionList[index].rightNum2 = this.answer_list.indexOf(this.questionList[index].answer)
      this.currentIndex = index
      this.commitKey = key
      this.rightAnswerArray[index] = this.options.indexOf(this.questionList[index].answer)
      this.rightAnswer = this.questionList[index].rightNum
      for (var k = 0; k < this.commitAnswer.length; k++) {
        this.MultiSelection[index].active = true
      }
      // console.log(this.MultiSelection)
    },
    // 收藏
    addToCollect (index, id) {
      console.log(index, id)
      let that = this
      if (this.questionList[index].collection === 1) {
        this.questionList[index].collection = 0
        this.$http.post('https://dati.co-links.com/operat/del_collection', {
          userid: that.userid,
          questionid: id
        }).then((res) => {
          console.log(res)
        })
      } else {
        this.questionList[index].collection = 1
        this.$http.post('https://dati.co-links.com/operat/collection/', {
          userid: that.userid,
          questionid: id
        }).then((res) => {
          console.log(res)
        })
      }
    },
    nextQuestion () {
      if (this.index === this.questionList.length - 1) {
        this.lastQuestion = true
        clearInterval(this.timer)
        console.log(this.currentIndex)
        console.log(this.commitAnswer.length)
        this.clickAnswer = ''
        // this.commitAnswer[this.currentIndex].res = this.commitKey
        this.commitAnswer[this.currentIndex] = {
          index: this.currentIndex,
          id: this.questionList[this.currentIndex].id,
          res: this.commitKey,
          right: this.commitKey === this.options.indexOf(this.questionList[this.currentIndex].answer) ? 1 : 0
        }
        for (var i = 0; i < this.commitAnswer.length; i++) {
          console.log('当前i', i)
          console.log(this.commitAnswer[i])
          if (this.commitAnswer[i]) {

            // if (this.commitAnswer[i].res !== undefined && i < this.questionList.length) {
            //   console.log(i, this.commitAnswer[i])
            //   this.count++
            //   console.log(this.count)
            // }
          } else {
            this.commitAnswer[i] = {
              index: i,
              id: this.questionList[i].id,
              res: undefined,
              right: 0
            }
          }
        }
        // 计算count值  20180815
        // console.log(this.MultiSelection)
        for (let k = 0; k < this.MultiSelection.length; k++) {
          if (this.MultiSelection[k].active) {
            this.count++
          }
        }
        // 8-16  修改
        // this.currentIndex = -1
        this.commitKey = ''
        this.setExamPaper({
          rightAnswerArray: this.rightAnswerArray,
          commitAnswer: this.commitAnswer,
          paperId: this.examPaperId,
          collectId: [],
          clickArray: this.commitAnswer,
          totalNum: this.questionList.length
        })
        // return false
      } else {
        // 设置currentIndex  8/18
        this.currentIndex = this.index
        console.log(this.currentIndex)
        this.commitAnswer[this.currentIndex] = {
          index: this.currentIndex,
          id: this.questionList[this.currentIndex].id,
          res: this.commitKey,
          right: this.commitKey === this.options.indexOf(this.questionList[this.currentIndex].answer) ? 1 : 0
        }
        // this.commitAnswer[this.currentIndex].res = this.commitKey
        // 8-16  修改
        // this.currentIndex = -1
        this.commitKey = ''
        console.log(this.commitAnswer)
        this.setExamPaper({
          clickArray: this.commitAnswer
        })
        this.index++
      }
    },
    // 计时
    fill_zero_prefix (num) {
      return num < 10 ? '0' + num : num
    },
    startCountTime () {
      let that = this
      that.timer = null
      that.timer = setInterval(function () {
        that.startSecond = that.fill_zero_prefix(that.startSecond * 1 + 1)
        if (that.startSecond === 59) {
          that.startMin = that.fill_zero_prefix(that.startMin * 1 + 1)
          that.startSecond = that.fill_zero_prefix(0)
        }
        if (this.startMin === 59) {
          that.startHour = that.fill_zero_prefix(that.startHour * 1 + 1)
          that.startMin = that.fill_zero_prefix(0)
        }
      }, 1000)
    },
    arrayUnique2 (arr, name) {
      let hash = {}
      return arr.reduce(function (item, next) {
        hash[next[name]] ? '' : hash[next[name]] = true && item.push(next)
        return item
      }, [])
    },
    navToMenu (flag) {
      if (flag) {
        this.lastQuestion = false
        this.showQuestion = true
      } else {
        this.lastQuestion = true
      }
      // console.log(this.lastQuestion)
      this.showmenuMain = true
      this.count = 0
      console.log(this.commitAnswer)
    },
    navToScore () {
      let that = this
      console.log(this.rightAnswerArray)
      console.log(this.currentIndex, '当前currentIndex')
      console.log(JSON.stringify(this.commitAnswer))
      for (let i = 0; i < this.questionList.length; i++) {
        if (this.commitAnswer[i]) {
        } else {
          this.commitAnswer[i] = {
            index: i,
            id: this.questionList[i].id,
            res: undefined,
            right: 0
          }
        }
      }
      // 记录答对的题目数量
      for (var i = 0; i < this.rightAnswerArray.length; i++) {
        console.log(this.commitAnswer)
        if ((this.rightAnswerArray[i] === this.commitAnswer[i].res) && this.rightAnswerArray[i] !== undefined) {
          this.rightTotal++
        }
      }
      // 提交后台的数据
      this.setExamPaper({
        rightTotal: this.rightTotal,
        time: this.startHour * 3600 + this.startMin * 60 + this.startSecond * 1,
        totalNum: this.questionList.length,
        commitAnswer: this.commitAnswer,
        rightAnswerArray: this.rightAnswerArray,
        rightAnswer: this.rightAnswer,
        examType: this.$mp.query.type
      })
      this.$http.post('https://dati.co-links.com/operat/recording/', {
        paperid: that.examPaperId,
        userid: that.userid,
        user_answer_list: JSON.stringify(this.commitAnswer),
        long_time: that.startHour * 3600 + that.startMin * 60 + that.startSecond * 1,
        push_type: 1,
        papername: that.$mp.query.name
      }).then((res) => {
        that.setExamResult({
          grade: res.data.data.grade,
          long_time: res.data.data.long_time,
          paper_name: res.data.data.paper_name,
          correct_num: res.data.data.correct_num
        })
        console.log(res)
      })
      if (this.startHour > 0) {
        this.totalTime += parseInt(this.startHour)
      }
      if (this.startMin >= 0 && this.startHour > 0) {
        this.totalTime += parseInt(this.startMin)
      }
      if (this.startSecond >= 0) {
        this.totalTime += parseInt(this.startSecond)
      }
      // console.log(this.totalTime)
      // 设置考试记录  相关试题 时间  试卷名称
      // console.log(this.examPaper)
      this.setformalRecord({
        paperId: this.examPaperId,
        // paperName: this.examPaper.paperName,
        time: this.startHour * 3600 + this.startMin * 60 + this.startSecond * 1,
        detailTime: formatTime(new Date()),
        score: parseInt(100 / this.questionList.length * this.rightTotal),
        finishStatus: 1,
        paperTest: this.questionList,
        commitAnswer: this.commitAnswer,
        rightAnswerArray: this.rightAnswerArray
      })
      // 存取考试记录
      var randomHash = 'paperHash' + parseInt(Math.random() * 100000)
      this.examRecord = {
        paperHash: randomHash,
        type: 'formalTest',
        paperId: this.examPaperId,
        // paperName: this.examPaper.paperName,
        time: this.startHour * 3600 + this.startMin * 60 + this.startSecond * 1,
        detailTime: formatTime(new Date()),
        score: parseInt(100 / this.questionList.length * this.rightTotal)
      }
      wx.setStorageSync(randomHash, this.examRecord)
      wx.redirectTo({
        url: '../tranScore/main?type=formal'
      })
    },
    prevQuestion () {
      if (this.index === 0) {
        return false
      } else {
        this.index--
      }
    },

    addActive (i) {
      // this.MultiSelection[i].active = true
      this.showmenuMain = false
      this.lastQuestion = false
      this.showQuestion = false
      this.index = i
      this.currentIndex = i
      // console.log('../simulationTest/main?type=' + 'random' + '&id=' + this.$mp.query.examPaperId + '&defaultItem=' + i + '&lastQuestion=' + true)
      // wx.reLaunch({
      //   url: '../simulationTest/main?type=' + 'random' + '&id=' + this.$mp.query.examPaperId + '&defaultItem=' + i + '&lastQuestion=' + true
      // })
    },
    naviBack () {
      this.showmenuMain = false
      this.lastQuestion = false
      this.showQuestion = false
    },
    init () {
      let that = this
      this.userid = this.userInfo.user_id || wx.getStorageSync('user_id')
      this.testpaperId = that.$mp.query.id
      wx.showLoading({
        title: '加载中'
      })
      this.$http.get('https://dati.co-links.com/exam/get_paper', {
        paperid: that.$mp.query.id,
        userid: that.userid
      }).then((res) => {
        that.questionList = res.data.data.questions
        if (res.data.data.questions.length === 0) {
          that.noData = true
        }
        wx.hideLoading()
        if (that.questionList.length > 0) {
          clearInterval(that.timer)
          that.startCountTime()
        }
        // console.log(that.questionList[0].collection)
        for (var i in that.questionList) {
          that.questionList[i].res = -1
          that.questionList[i].hide = true
        }
        that.MultiSelection = []
        that.examPaperId = that.$mp.query.id
        that.index = that.$mp.query.defaultItem * 1
        for (var m = 0; m < that.questionList.length; m++) {
          that.MultiSelection.push({
            active: false
          })
        }
        console.log(that.MultiSelection)
      })
    }
  },
  mounted () {
    this.init()
    this.commitAnswer = []
    this.rightAnswerArray = []
    this.noData = false
    this.questionList = []
    this.showmenuMain = false
    this.lastQuestion = false
    this.showQuestion = false
    this.count = 0
    console.log('formal mounted')
    this.startSecond = '00'
    this.startMin = '00'
    this.startHour = '00'
    if (this.startHour === 0) {
      this.startHour = '0' + this.startHour
    }
    if (this.startMin === 0) {
      this.startMin = '0' + this.startMin
    }
    if (this.startSecond === 0) {
      this.startSecond = '0' + this.startSecond
    }
    this.MultiSelection = []
    this.examPaperId = this.$mp.query.id
    this.index = this.$mp.query.defaultItem * 1
    if (this.formalRecord.finishStatus === 1) {
      // 试卷已提交  清空之前的状态
      this.lastQuestion = false
      this.showQuestion = false
      this.showmenuMain = false
      this.lastQuestion = false
      this.rightTotal = 0
      this.startSecond = '00'
      this.startMin = '00'
      this.startHour = '00'
      for (let i = 0; i < this.questionList.length; i++) {
        this.questionList[i].res = -1
      }
    }
  },
  onUnload () {
    console.log('onUnload')
    clearInterval(this.timer)
  }

}
</script>
 <style lang="stylus">
 .simulationMain {
   height: 100%;
 }

 .question {
   padding: 0 32rpx;
   margin-bottom: 20rpx;
   background: white;

   .questionNum {
     font-size: 30rpx;
     color: #333;
     height: 98rpx;
     line-height: 98rpx;
     border-bottom: 2rpx solid #e6e6e6;

     p {
       display: inline-block;
     }

     .p2 {
       float: right;
       width: 112rpx;

       span {
         display: inline-block;
         width: 112rpx;
         height: 46rpx;
         background: #febd32;
         color: white;
         font-size: 26rpx;
         text-align: center;
         line-height: 46rpx;
         border-radius: 6rpx;
         -webkit-border-radius: 6rpx;
       }
     }
   }

   .questionTitle {
     font-size: 32rpx;
     color: #333333;
     padding: 20rpx 0;
   }
 }

 .questionContent {
   padding-bottom: 30rpx;
 }

 .questionAnswer {
   p {
     font-size: 32rpx;
     color: #666666;
     padding: 18rpx 0;
     padding-left: 30rpx;

     span {
       display: inline-block;
       width: 48rpx;
       height: 48rpx;
       border-radius: 50%;
       margin-right: 30rpx;
       border: 1px solid #a5a5a5;
       text-align: center;
       line-height: 48rpx;
     }

     &.active {
       color: #ef5151;

       span {
         border: 1px solid #ef5151;
         background: #ef5151;
         color: white;
       }
     }

     &.right {
       color: #00cc76;

       span {
         background: #00cc76;
         color: #fff;
         border: 1px solid #00cc76;
       }
     }
   }
 }

 .analyseAnswer {
   padding: 20rpx 22rpx;
   background: #ebebeb;
   font-size: 32rpx;
   color: #333333;
   border-radius: 12rpx;
   -webkit-border-radius: 12rpx;

   p {
     line-height: 60rpx;
   }

   p:last-child {
     font-size: 28rpx;
   }
 }

 .markBottom {
   position: fixed;
   bottom: 0;
   left: 0;
   width: 100%;
   height: 90rpx;
   border-top: 2rpx solid #e6e6e6;
   background: white;

   p {
     display: inline-block;
     width: 25%;
     height: 100%;
     line-height: 90rpx;
     font-size: 50rpx;
     color: #333;
     text-align: center;

     span {
       display: inline-block;
       font-size: 28rpx;
       margin-left: 10rpx;
       line-height: 90rpx;
       height: 100%;
       vertical-align: top;
     }
   }
 }

 .examOver {
   text-align: center;
   display: none;
 }

 .examBg {
   width: 242rpx;
   height: 224rpx;
   padding-top: 180rpx;
 }

 .tips {
   text-align: center;
   font-size: 32rpx;
   color: #333333;
   padding-top: 50rpx;
 }

 .questionBtn {
   text-align: center;
   position: relative;
   margin-top: 200rpx;

   span, button {
     display: inline-block;
     width: 210rpx;
     height: 68rpx;
     line-height: 68rpx;
     text-align: center;
     border-radius: 10rpx;
     -webkit-border-radius: 10rpx;
     border: 2rpx solid #00cc76;
     font-size: 28rpx;
     color: #00cc76;
   }

   .next {
     background: #00cc76;
     color: white;
     margin-left: 88rpx;
   }

   .disabled {
     background: #ccc;
     color: white;
     border: 2rpx solid #ccc;
   }

   .nextBtn {
     display: none;
   }
 }

 .hide {
   display: none !important;
 }

 .show {
   display: block;
 }

 .questionBtn .show {
   display: inline-block;
 }

 .markBottom .collectActive {
   color: #ef5151;
 }

 .menuMain {
   background: #f7f7f7;
   display: none;
 }

 .menuMain&.showmenuMain {
   display: block;
 }

 .singleSelection, .MultiSelection, .checkSelection {
   padding: 0 32rpx;
   margin-bottom: 20rpx;
   background: white;

   .title {
     padding-top: 20rpx;
     font-size: 32rpx;
     color: #333333;
   }
 }

 .singleList {
   display: -webkit-box;
   display: -webkit-flex;
   display: flex;
   -webkit-box-align: center;
   -webkit-align-items: center;
   align-items: center;
   flex-wrap: wrap;
   padding-bottom: 30rpx;

   span {
     display: inline-block;
     width: 60rpx;
     height: 60rpx;
     border-radius: 50%;
     -webkit-border-radius: 50%;
     color: #666666;
     font-size: 32rpx;
     text-align: center;
     line-height: 60rpx;
     background: #e6e6e6;
     margin: 20rpx;

     &.active {
       background: #00cc76;
       color: white;
     }
   }
 }

 .topicSelect {
   padding-bottom: 100rpx;
 }

 .fixedBtn {
   position: fixed;
   bottom: 0;
   left: 0;
   width: 100%;
   text-align: center;
   height: 88rpx;
   border-top: 1px solid #e6e6e6;
   background: white;

   span {
     display: inline-block;
     margin-top: 8rpx;
     width: 292rpx;
     height: 72rpx;
     text-align: center;
     line-height: 72rpx;
     color: #ffffff;
     font-size: 28rpx;
     border-radius: 12rpx;
     -webkit-border-radius: 12rpx;
     background: #00cc76;

     &:nth-child(2) {
       margin-left: 38rpx;
     }
   }
 }

 .noData {
   position: fixed;
   height: 100%;
   width: 100%;
   left: 0;
   top: 0;
   z-index: 4;
   background: white;

   img {
     position: absolute;
     display: block;
     width: 300rpx;
     height: 300rpx;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
     margin: auto;
   }
 }
</style>

